﻿using DesktopLauncher.Helper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

namespace DesktopLauncher
{
    public partial class FrmMain : Form
    {
        bool allowCloseForm = false;
        public FrmMain()
        {
            InitializeComponent();
        }

        private readonly Dictionary<string, Action> actionMap = new Dictionary<string, Action>();
        private readonly FileInfoHelper fileInfoHelper = new FileInfoHelper();

        private static readonly char[] ShortKeys = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
        private void FrmMain_Load(object sender, EventArgs e)
        {
            lvIcons.Groups.Add(new ListViewGroup("设置"));
            SetWindowPos();
            SetDefaultIcon();
            ShowIcons();
            allowCloseForm = true;
        }

        private void SetDefaultIcon()
        {
            actionMap.Add(":SETTING", new Action(() =>
            {
                allowCloseForm = false;
                new FrmSetting().ShowDialog();
                allowCloseForm = true;
            }));
        }

        private void SetWindowPos()
        {
            int x = MousePosition.X;
            int y = MousePosition.Y;
            if (MousePosition.Y + this.Height > Screen.GetWorkingArea(MousePosition).Height)
                y = Screen.GetWorkingArea(MousePosition).Height - this.Height;
            if (MousePosition.X + this.Width > Screen.GetWorkingArea(MousePosition).Width)
                x = Screen.GetWorkingArea(MousePosition).Width - this.Width;
            this.Location = new Point(x, y);
        }
        private void ShowIcons()
        {
            string folderPath = System.Configuration.ConfigurationManager.AppSettings["FOLDER_PATH"];
            fileInfoHelper.FolderPath = folderPath;
            this.lvIcons.BeginUpdate();
            if (!string.IsNullOrWhiteSpace(folderPath) && System.IO.Directory.Exists(folderPath))
            {
                //get icons
                string[] files = FileInfoHelper.GetFileNames(System.IO.Directory.GetFiles(folderPath));

                List<FileInfoModel> fileInfos = fileInfoHelper.GetCachedFileInfo();
                if (!FileInfoHelper.CompareFileInfo(files, fileInfos))
                    fileInfos = fileInfoHelper.ReadAndCacheFileInfo(this.Handle, files);

                SetListViewIconList(fileInfos.Select(a => a.Icon).ToList());

                for (int i = 0; i < fileInfos.Count; i++)
                {
                    String showText = fileInfos[i].FileNameWithoutExtension;
                    if (i < ShortKeys.Length)
                        showText = $"({ShortKeys[i]}) " + showText;
                    this.lvIcons.Items.Add(new ListViewItem()
                    {
                        Text = showText,
                        Tag = fileInfos[i].FileName,
                        ImageIndex = i,
                        Group = lvIcons.Groups[0],
                    });
                    string filePath = fileInfos[i].FilePath;
                    actionMap.Add(fileInfos[i].FileName, new Action(() =>
                    {
                        var proc = new System.Diagnostics.Process();
                        proc.StartInfo.FileName = filePath;
                        try
                        {
                            proc.Start();
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                        }
                        this.Close();
                    }));
                }


            }
            else
            {
                SetListViewIconList(new List<Image>());
                MessageBox.Show("请设置存放快捷方式的文件夹");
            }
            this.lvIcons.Items.Add(new ListViewItem()
            {
                Text = "设置",
                Tag = ":SETTING",
                Group = lvIcons.Groups[1],
                ImageIndex = this.lvIcons.LargeImageList.Images.Count - 1
            });
            this.lvIcons.EndUpdate();
        }



        private void lvIcons_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            if (actionMap.ContainsKey((string)e.Item.Tag))
            {
                actionMap[(string)e.Item.Tag]();
            }
        }

        private void SetListViewIconList(List<Image> list)
        {
            var imageList = new ImageList
            {
                ImageSize = new Size(48, 48),
                ColorDepth = ColorDepth.Depth32Bit
            };
            for (int i = 0; i < list.Count; i++)
            {
                Image ico = list[i];
                imageList.Images.Add(ico);
            }

            //add system icon
            imageList.Images.Add(IconHelper.SettingIcon.ToBitmap());
            imageList.Images.Add(IconHelper.ExitIcon.ToBitmap());

            this.lvIcons.LargeImageList = imageList;
        }

        private void lvIcons_ItemMouseHover(object sender, ListViewItemMouseHoverEventArgs e)
        {
            foreach (ListViewItem item in lvIcons.Items)
            {
                item.ForeColor = SystemColors.WindowText;
                item.BackColor = Color.White;
            }
            e.Item.ForeColor = SystemColors.HighlightText;
            e.Item.BackColor = SystemColors.Highlight;
        }

        private void FrmMain_Deactivate_1(object sender, EventArgs e)
        {
            if (allowCloseForm)
                this.Close();
        }

        private void LvIcons_KeyDown(object sender, KeyEventArgs e)
        {
            char pressedChar = ConvertHelper.KeyToChar(e.KeyData);
            int index = -1;
            for (int i = 0; i < ShortKeys.Length; i++)
                if (ShortKeys[i] == pressedChar)
                {
                    index = i;
                    break;
                }

            if (index > -1)
            {                
                if (actionMap.ContainsKey((string)lvIcons.Items[index].Tag))
                {
                    actionMap[(string)lvIcons.Items[index].Tag]();
                }
            }
        }
    }
}
